package top.hooray.delayedpayment.controller;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import top.hooray.delayedpayment.entity.Order;
import top.hooray.delayedpayment.entity.OrderDetail;
import top.hooray.delayedpayment.entity.OrderStatus;
import top.hooray.delayedpayment.service.OrderService;
import top.hooray.delayedpayment.util.SnowflakeId;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * @author hooray
 * @date 2021/3/9 22:58
 */
@Controller
public class OrderController {

    private final RabbitTemplate rabbitTemplate;
    private final SnowflakeId snowflakeId;
    private final OrderService orderService;

    public OrderController(RabbitTemplate rabbitTemplate, OrderService orderService) {
        this.rabbitTemplate = rabbitTemplate;
        this.orderService = orderService;
        this.snowflakeId = new SnowflakeId(10, 10, 10);
    }

    @RequestMapping("/order")
    public String order(Model model) throws ExecutionException, InterruptedException {
        //简单的造下数据
        List<OrderDetail> details = new ArrayList<>();
        OrderDetail od = new OrderDetail();
        od.setItemId(snowflakeId.nextId());
        od.setItemName("香蕉");
        od.setItemPrice(new BigDecimal(125));
        od.setNum(5);
        details.add(od);

        Order order = new Order();
        order.setOrderId(snowflakeId.nextId());
        order.setUserId(UUID.randomUUID().toString());
        // 设置状态为待支付
        order.setStatus(OrderStatus.UNPAID);
        order.setOrderDetails(details);

        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend("ex.order", "key.order", order, correlationData);
        // 同步等待；可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        if (!confirm.isAck()) {
            return "fail_order";
        }
        // 发送延迟等待消息
        rabbitTemplate.convertAndSend("ex.ttl", "key.ttl", order.getOrderId());
        model.addAttribute("orderId", order.getOrderId());
        return "order";
    }

    @RequestMapping("/fail_order/{orderId}")
    public String failOrder(@PathVariable Long orderId, Model model) {
        model.addAttribute("order", orderService.findOrderById(orderId));
        return "fail";
    }
}
